from django.contrib import admin
from app01.models import *
from django.utils.safestring import mark_safe
from django.core.mail import send_mail
from threading import Thread
from django.conf import settings
from api.models import Email


class UserInfoAdmin(admin.ModelAdmin):
    def get_avatar(self: UserInfo):
        if self.sign_status in [1, 2]:
            return mark_safe(f'<img src="{self.avatar_url}" style="width:30px; height:30px;border-radius:5px;">')
        return mark_safe(f'<img src="{self.avatar.url.url}" style="width:30px; height:30px;border-radius:5px;">')

    get_avatar.short_description = '头像'

    def get_user_name(self):
        if not self.sign_status:
            return self.username
        return '******'

    get_user_name.short_description = '用户名'
    list_display = [get_user_name, 'nick_name', get_avatar, 'sign_status', 'is_superuser', 'date_joined', 'login_date',
                    'last_login']

    def get_avatar_action(self, request, queryset):
        for obj in queryset:
            if not obj.sign_status:
                continue
                # 其他平台注册的
    get_avatar_action.short_description = '获取用户信息'
    actions = [get_avatar_action]


class ArticleAdmin(admin.ModelAdmin):
    def get_cover(self):
        if self.cover:
            return mark_safe(f'<img src="{self.cover.url.url}" style="height:60px;">')
        return '暂无封面'

    get_cover.short_description = '文章封面'

    def get_tags(self):
        return ','.join([i.title for i in self.tag.all()])

    get_tags.short_description = '文章标签'

    def get_title(self):
        return mark_safe(f'<a href="/article/{self.nid}/" target="_blank">{self.title}</a>')

    get_title.short_description = '文章地址'

    # 一般地址是用反向解析的，但是这里用了自定义的，所以需要设置反向解析的url
    def get_edit_delete(self):
        return mark_safe(
            f"""
            <a href="/backend/edit_article/{self.nid}/" target="_blank">编辑</a>
            <a href="/admin/app01/articles/{self.nid}/delete">删除</a>
            """
        )

    get_edit_delete.short_description = '操作'

    list_display = [get_title,
                    get_cover,
                    get_tags,
                    'category',
                    'look_count',
                    'digg_count',
                    'comment_count',
                    'collects_count',
                    'word', 'change_date',
                    get_edit_delete]  # 显示字段

    def action_word(self, request, queryset):
        for obj in queryset:
            word = len(obj.content)
            obj.word = word
            obj.save()

    action_word.short_description = '获取文章字数'
    actions = [action_word]


# 站点背景图
class MenuImgAdmin(admin.ModelAdmin):
    def getImg(self):
        if self.url:
            return mark_safe(f"""
            <img src="{self.url.url}" style="height:50px;">
            """)

    list_display = ['url', getImg]
    getImg.short_description = '背景图'


admin.site.register(MenuImg, MenuImgAdmin)


# 菜单
class MenuAdmin(admin.ModelAdmin):
    add_form_template = 'simple_admin/add_form.html'
    change_form_template = 'simple_admin/add_form.html'

    def get_menu_url(self: Menu):
        lis = [f"<img src='{i.url.url}' style='height:60px;margin-right:5px;'>" for i in self.menu_url.all()]
        return mark_safe(''.join(lis))

    get_menu_url.short_description = '图片组'
    list_display = ['menu_title', 'menu_title_en',
                    'title', 'abstract',
                    'rotation', 'abstract_time',
                    'menu_rotation', 'menu_time', get_menu_url]


# 意见反馈
class FeedBackAdmin(admin.ModelAdmin):
    list_display = ['email', 'content', 'status', 'processing_content']

    def has_add_permission(self, request):
        return False

    def save_model(self, request, obj, form, change):  # change == true :编辑
        if not change:
            return
        email = obj.email
        obj.status = True
        processing_content = form.data.get('processing_content')

        msg_from = settings.EMAIL_HOST_USER  # 发送人地址
        to = [email, ]  # 收件人地址
        subject = 'dkzcm个人博客的反馈邮件'  # 电子邮件主题
        contents = processing_content  # 发送内容
        Thread(target=send_mail, args=(
            subject,
            contents,
            msg_from,
            to,
            False
        )).start()
        Email.objects.create(
            email=email,
            content=processing_content,

        )
        return super(FeedBackAdmin, self).save_model(request, obj, form, change)


# Register your models here.
admin.site.register(Articles, ArticleAdmin)
admin.site.register(Tags)
admin.site.register(Cover)
admin.site.register(Comment)
admin.site.register(Moods)
admin.site.register(MoodComment)
admin.site.register(Avatars)
admin.site.register(UserInfo, UserInfoAdmin)
admin.site.register(Menu, MenuAdmin)
admin.site.register(Feedback, FeedBackAdmin)
admin.site.register(History)
